R Advanced Course

Working with R Markdown and Leaflet

Objective and contents

Objective and contents

Objective: to create reports in PDF and HTML formats.

  • Introduction to R Markdown
  • Creating and compiling reports with code in PDF
  • Introduction to Leaflet

Introduction to R Markdown

R Markdown

The rmarkdown package helps to create documents that combine code, rendered output, and text. These documents can help to:

  • Reproduce your analysis and reports

  • Communicate your results better

  • Do data science interactively

R Markdown can render documents in PDF, HTML, Word, slideshows among others. You can read the R Markdown: The Definitive Guide book.

Installation

You can install the rmarkdown package as follows:

# Install from CRAN
install.packages('rmarkdown')

# Or if you want to test the development version, install it from GitHub
install.packages('devtools')
devtools::install_github('rstudio/rmarkdown')

In case that you want to render PDF documents you need to install LaTeX. For this purpose, TinyTeX is reccomended https://yihui.name/tinytex/.

install.packages('tinytex')
tinytex::install_tinytex()

Work with R Markdown

The R scripts have the .R as file extension, while R Markdown documents have :Rmd. Once that the rmarkdown package is installed you will be able to open a new Rmd file as follows:

File -> New File -> R Markdown

Work with R Markdown

When you create the document you will see something like this:

Work with R Markdown

The first segment of the document indicate its information (e.g., the title, author, and date) and characteristics (e.g., the output format).

---
title: "Test"
author: "Oscar M. Baez-Villanueva"
date: "4/27/2022"
output: pdf_document
---
You can render the file clicking the Knit button in the top of the script area. Please save your file as Test.Rmd.

Work with R Markdown

The result is:

Work with R Markdown

Please note that you have text and code embedded in the same document. To add text, you have simply to write it. To add code, you have to embed it inside a code chunk, which starts and ends with three backticks ```.

r indicates the name of the programming language.This code chunk can have several options that must be added between the programming language (r) and the closing curly bracket (}).

Chunk options

You can insert a new code chunk with the keyboard shorcut Ctrl + Alt + I (OS X: Cmd + Option + I).

eval = FALSE prevents code to run. It will serve just for rendering purposes.

include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.

echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.

Chunk options

message = FALSE prevents messages that are generated by code from appearing in the finished file.

warning = FALSE prevents warnings that are generated by code from appearing in the finished.

fig.align aligns the figure to the ‘center’, ‘right’ or ‘left’.

fig.cap = “…” adds a caption to graphical results.

Output formats

There are several formats available in rmarkdown:

  • pdf_document
  • html_document
  • beamer_presentation
  • github_document
  • ioslides_presentation
  • latex_document
  • pdf_document
  • powerpoint_presentation
  • slidy_presentation
  • word_document

Syntax

The text in an R Markdown document is written in Pandoc’s Markdown.

italics: surrounded by underscores (_) or asterisks(*); e.g., italics.

bold: surrounded by double underscores (__) or asterisks(**); e.g., bold.

subscript: surrounded by tildes (~); e.g., wordsubscript.

superscript: surrounded by tildes (^); e.g., wordsuperscript.

inline code: surrounded by backticks (`); e.g., code.

To add bibliography please visit Section 2.8 of Authoring Books with R Markdown.

Creating and compiling reports with code in PDF

Random numbers

Let’s create a simple PDF document as an example and name it Random numbers.

---
title: "Random numbers"
author: "Oscar M. Baez-Villanueva"
date: "`r Sys.Date()`"
output: pdf_document
---

Later on, we can add a code chunk to specify that all code should be visible.

 ```{r setup, include=FALSE}
      knitr::opts_chunk$set(echo = TRUE)
 ``` 

Random numbers

We can add some text:

We will use the function norm to generate a matrix of 60 normally distributed random values with six columns:
```{r}
x <- matrix(rnorm(60), ncol = 6)
print(x)
```

Random numbers

Then, some more text:

We can calculate the mean value of all values:
```{r}
vals <- as.numeric(x)
m    <- mean(vals)
```

Random numbers

Additionally, we can show values stored in variables in the text as follows:

The mean value of these numbers is: `r m`. Additionally, `r max(vals)` is the maximum value, and `r min(vals)` the minimum.

Finally, we can use the function boxplot to visualise the data:

```{r fig.align='center', fig.cap="Boxplot of random numbers"}
boxplot(x)
```

Rendered document

Leaflet

Leaflet

Leaflet is a widely used open-source JavaScript library for interactive maps. The leaflet package helps you to integrate and control Leaflet maps in R. This package will help you to render spatial data and share the results in a very interesting way.

Please install the leaflet package.

install.packages("leaflet")

Now, lease load it:

library(leaflet)

Leaflet

Let’s create a basic map widget:

m <- leaflet()
m <- setView(m, lng = -99.179, lat =  21.801, zoom = 5)
m <- addTiles(m)
m <- addMarkers(m, lng = -99.179, lat = 21.801, popup = "A place to visit!")
m

Additionally, we can use the magrittr pipe:

m <- leaflet() %>%
  setView(lng = -99.179, lat =  21.801, zoom = 5) %>%
  addTiles() %>%
  addMarkers(lng = -99.179, lat = 21.801, popup = "A place to visit!")
m

Leaflet

Leaflet

There are several nice map themes here.

m <- leaflet(width="100%") %>%
  setView(lng = -99.179, lat =  21.801, zoom = 5) %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
  addMarkers(lng = -99.179, lat = 21.801, popup = "A place to visit!")
m

Adding vector data

We can add polygons to the plots. Let’s read the shapefile of a catchment in Chile and its river network with the sf package.

catch  <- "C:/Data/Shapefile/Trancura_catchment.shp"
rivers <- "C:/Data/Shapefile/Trancura_rivers.shp"
catch  <- read_sf(catch)
rivers <- read_sf(rivers)

Let’s plot the data:

leaflet(width="100%") %>% 
 addTiles() %>% 
 addPolygons(data=catch, weight = 3, color = "blue")

Adding vector data

Adding vector data

leaflet(width="100%") %>% 
 addTiles() %>% 
 addPolygons(data=catch, weight = 3, color = "blue", popup = ~ NOMBRE, group = "Catchment") %>%
 addPolygons(data=rivers, weight = 3, color = "cyan", group = "Rivers") %>%
 addLayersControl(
   overlayGroups = c("Catchment", "Rivers"),
   options = layersControlOptions(collapsed = FALSE)
 )

Adding raster data

Let’s use the raster package to import the raster layers as the terra package is still not supported by leaflet.

rfmep <- "../Data/L5_RMarkdown/Raster/RF-MEP_1990-2018_multiannual.tif"
mswep <- "../Data/L5_RMarkdown/Raster/MSWEPv2.8_1990-2018_multiannual.tif"
rfmep <- raster(rfmep)
mswep <- raster(mswep)

r <- stack(rfmep, mswep)

pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
  na.color = "transparent")

Adding raster data

To add raster files:

leaflet(width="100%") %>% 
 addTiles() %>% 
 addRasterImage(r[[1]], colors = pal, opacity = 0.8, group = "RF-MEP") %>%
 addRasterImage(r[[2]], colors = pal, opacity = 0.8, group = "MSWEPv2.8") %>%
 addPolygons(data=catch, weight = 3, color = "blue", popup = ~ NOMBRE, group = "Catchment") %>%
 addPolygons(data=rivers, weight = 3, color = "cyan", group = "Rivers") %>%
 addLegend(pal = pal, values = values(r), title = "P [mm]") %>%
 addLayersControl(
   baseGroups = c("RF-MEP", "MSWEPv2.8"),
   overlayGroups = c("Catchment", "Rivers"),
   options = layersControlOptions(collapsed = FALSE),
 )